package com.whccb.apps.office.document.ui;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import com.actionsoft.bpms.bo.design.cache.BOCache;
import com.actionsoft.bpms.bo.design.model.BOItemModel;
import com.actionsoft.bpms.bo.design.model.BOModel;
import com.actionsoft.bpms.commons.htmlframework.HtmlPageTemplate;
import com.actionsoft.bpms.ui.base.AbstractUIComponent;
import com.actionsoft.bpms.ui.base.UIContext;
import com.actionsoft.bpms.util.Html;
import com.actionsoft.bpms.util.UtilSerialize;
import com.actionsoft.bpms.util.UtilString;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONObject;
import com.whccb.apps.office.document.ODConstant;

public class ShortTextFieldUI extends AbstractUIComponent {

	public ShortTextFieldUI(UIContext context) {
		super(context);
	}

	public String getConfigWebPage(UIContext context) {
		Map<String, Object> macroLibraries = new HashMap<String, Object>();
		macroLibraries.put("appId", ODConstant.APP_ID);
		return HtmlPageTemplate.merge(ODConstant.APP_ID,
				"com.whccb.apps.office.document.ui.shorttextfieldConfig.htm",
				macroLibraries);
	}

	@Override
	public String getInitScript(UIContext context, boolean readOnly) {
		return "";
	}

	@Override
	public String getUI(UIContext context, boolean readOnly) {

		boolean isMobile = isMobile(context.getUserContext());
		BOItemModel boItemModel = context.getBoItemModel();
		StringBuilder html = new StringBuilder();
		if (readOnly) {
			html.append(getReadonlyUI(context));
			return html.toString();
		}
		StringBuilder fieldHtml = new StringBuilder();

		fieldHtml
				.append("<input type='text' style='width: 30px;text-align:center; vertical-align:middle' readonly='readonly'")
				.append(" title='")
				.append(SDK.getRuleAPI().executeAtScript(
						boItemModel.getTooltip(), context)).append("' ");
		String value = context.getValue();
		value = getShowValue(boItemModel, value);
		fieldHtml.append("  name='").append(boItemModel.getName())
				.append("' id='").append(boItemModel.getName()).append("'")
				.append("  value=\"").append(Html.escape(value)).append("\" >");

		StringBuilder isNotNull = new StringBuilder();
		if (!boItemModel.isNullable()) {
			isNotNull.append("<span class='required'>")
					.append(fieldHtml.toString()).append("</span>");
			return isNotNull.toString();
		}
		if (isMobile) {
			return "<span class ='mui-input-row'>" + fieldHtml.toString()
					+ "</span>";
		}
		return fieldHtml.toString();

	}

	@Override
	public String getValidateScript(UIContext context, boolean readOnly) {
		BOItemModel boItemModel = context.getBoItemModel();
		JSONObject configJson = super.getConfigJson(boItemModel, context);
		String boName = "";
		BOModel model = (BOModel) BOCache.getInstance().getModel(
				boItemModel.getBoModelId());
		if (model != null) {
			boName = model.getName();
		}
		return "UIValidate.validateUIComponentNumber('" + boName + "','"
				+ boItemModel.getName() + "','"
				+ getI18NValue(context, boItemModel.getTitle()) + "',"
				+ Html.encodeForJSON(configJson.toString())
				+ ",cellvalue, record)\n";
	}

	public static String getShowValue(BOItemModel boItemModel, String itemValue) {
		if (!UtilString.isEmpty(itemValue)) {
			String len = boItemModel.getLength();
			DecimalFormat df = getDecimalFormat(len);
			try {
				Double db = Double.valueOf(Double.parseDouble(itemValue));
				itemValue = df.format(db);
			} catch (NumberFormatException e) {
				return itemValue;
			}

		}

		String componentSetting = boItemModel.getComponentSetting();
		if ((UtilString.isEmpty(componentSetting))
				|| (componentSetting.equals("{}"))) {
			componentSetting = "{isShowZero:0}";
		}
		com.alibaba.fastjson.JSONObject settingObject = UtilSerialize
				.parseObject(componentSetting);
		String isShowZero = settingObject.getString("isShowZero") == null ? "0"
				: settingObject.getString("isShowZero");

		if ((UtilString.isEmpty(itemValue)) && (!isShowZero.equals("1"))) {
			itemValue = "0";
			if (boItemModel.getLength().indexOf(",") > -1) {
				itemValue = itemValue + ".";
				for (int n = 0; n < Integer.valueOf(
						boItemModel.getLength().substring(
								boItemModel.getLength().indexOf(",") + 1))
						.intValue(); n++) {
					itemValue = itemValue + "0";
				}
				if (itemValue.endsWith(".")) {
					itemValue = itemValue.substring(0, itemValue.length() - 1);
				}
			}
		}

		if (isShowZero.equals("1")) {
			Double number = Double.valueOf(0.0D);
			try {
				if (!UtilString.isEmpty(itemValue))
					number = Double.valueOf(Double.parseDouble(itemValue));
			} catch (Exception e) {
				e.printStackTrace();
			}
			if ((number == null) || (number.doubleValue() == 0.0D))
				itemValue = "";
		}
		return itemValue;
	}

	public static DecimalFormat getDecimalFormat(String len) {
		int numLong = 0;
		int numPrecision = 0;
		if (len.contains(",")) {
			numLong = Integer.parseInt(len.substring(0, len.indexOf(",")));
			numPrecision = Integer.parseInt(len.substring(len.indexOf(",") + 1,
					len.length()));
		} else {
			numLong = Integer.parseInt(len);
		}
		String s = "";
		for (int i = 0; i < numLong; i++) {
			s = s + "#";
		}
		if (len.contains(",")) {
			s = s + "0";
			s = s + ".";
			for (int i = 0; i < numPrecision; i++) {
				s = s + "0";
			}
			s = s.substring(numPrecision);
		}
		return new DecimalFormat(s);
	}

}
